package com.fz.us.oa.web.controller.main.company;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.Result;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.page.PageHelp;
import com.fz.us.admin.base.bean.search.result.SearchResultList;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.bean.search.rule.Rule;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.base.utils.EntityConfig;
import com.fz.us.admin.company.entity.*;
import com.fz.us.admin.company.service.CommonConfigService;
import com.fz.us.admin.company.service.DepartmentService;
import com.fz.us.admin.company.service.PostService;
import com.fz.us.admin.company.service.ProcessBriefService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 控制器 - 岗位信息
 * ============================================================================
 * 版权所有 2016 。
 *
 * @author fallenpanda
 * @version 1.0 2016-08-09 。
 * ============================================================================
 */
@Controller
@RequestMapping(value = "/main/processBrief")
public class ProcessBriefController extends BaseController {


    private static final long serialVersionUID = 8156014987612834287L;

    @Autowired
    private CommonConfigService commonConfigService;
    @Autowired
    private ProcessBriefService processBriefService;

    private static final EntityConfig entityConfig  = new EntityConfig();
    /**
     * 新建页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model, String keyId) {
        List<Map<String,Object>> entityDatas = Lists.newArrayList();
        ProcessBrief processBrief = null;
        CommonConfig creadConfig = null;
        CommonConfig ceditConfig = null;
        CommonConfig cdocConfig = null;
        if (StringUtils.isNotEmpty(keyId)) {
            processBrief =  processBriefService.get(keyId);
            List<Map<String,Object>> mapList = entityConfig.getAllProperties();
            Map<String,Object> rmap;
            for(Map map:mapList){
                rmap = Maps.newHashMap();
                rmap.put("key", map.get("key").toString());
                rmap.put("value", map.get("value").toString());
                rmap.put("selected", "");
                if(processBrief.getTableKey()!=null && StringUtils.equals(processBrief.getTableKey(), map.get("key").toString())){
                    rmap.put("selected", "selected");
                }
                entityDatas.add(rmap);
            }
            creadConfig = processBrief.getReadConfig();
            ceditConfig = processBrief.getEditConfig();
            cdocConfig = processBrief.getDocConfig();
            /*
            if (processBrief.getReadConfig() != null) {
                rselectType = processBrief.getReadConfig().getStype();
            }
            if (processBrief.getEditConfig() != null) {
                eselectType = processBrief.getEditConfig().getStype();
            }
            if (processBrief.getDocConfig() != null) {
                dselectType = processBrief.getDocConfig().getStype();
            }*/
        }else{
            entityDatas = entityConfig.getAllProperties();
        }
        model.addAttribute("keyId", keyId);
        model.addAttribute("entityDatas", entityDatas);
        model.addAttribute("processBrief", processBrief);
        model.addAttribute("creadConfig", creadConfig);
        model.addAttribute("ceditConfig", ceditConfig);
        model.addAttribute("cdocConfig", cdocConfig);
        return "/main/company/processBrief_input";
    }



    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user, String archReaderId,String archEditorId,String docReaderId,String keyId,
                       String processName,String tableKey, String share) {
        Map<String,Object> rMap=new HashMap<String,Object>();
        CommonConfig creadConfig = null;
        CommonConfig ceditConfig= null;
        CommonConfig cdocConfig= null;
        ProcessBrief processBrief ;
        if (StringUtils.isNotEmpty(archReaderId)){
            creadConfig = commonConfigService.get(archReaderId);
        }
        if (StringUtils.isNotEmpty(archEditorId)){
            ceditConfig = commonConfigService.get(archEditorId);
        }
        if (StringUtils.isNotEmpty(docReaderId)){
            cdocConfig = commonConfigService.get(docReaderId);
        }
        if(StringUtils.isNotEmpty(keyId)){
            processBrief = processBriefService.get(keyId);
        }else{
            processBrief = new ProcessBrief();
            processBrief.setCreater(user);
        }
        processBrief.setShare(share);
        processBrief.setName(processName);
        processBrief.setTableKey(tableKey);
        processBrief.setDocConfig(cdocConfig);
        processBrief.setReadConfig(creadConfig);
        processBrief.setEditConfig(ceditConfig);
        processBrief.setCompany(user.getCompany());
        if(StringUtils.isNotEmpty(keyId)){
            processBriefService.update(processBrief);
            rMap.put("message", "更新成功");
        }else{
            keyId =  processBriefService.save(processBrief);
            rMap.put("message","保存成功");
        }
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }





    /**
     * 操作
     */
    @RequestMapping(value = "delete/{keyId}", method = RequestMethod.POST)
    public Object method(@CurrentUser User user,
                         @PathVariable String keyId) {
        if(StringUtils.isNotEmpty(keyId)){
            ProcessBrief processBrief = processBriefService.get(keyId);
            processBrief.setState(BaseEnumManager.StateEnum.Delete);
            processBriefService.update(processBrief);
            return ajaxJson(resultService.successWithId(keyId));
        }else{
            return ajaxJson(resultService.fail());
        }
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
         /*
        // 排序
        Order order = null;

        if (StringUtils.isNotBlank(pager.getSidx()) && StringUtils.isNotBlank(pager.getSord())) {
            order = Order.order(pager.getSidx(), SearchEnum.OrderType.valueOf(pager.getSord()));
        }*/

      //  List<Rule> rules = getSearchFilterRules(pager.getSearch(), filters);
        SearchResultPaging searchResult = processBriefService.pagingProcessBrief(null, null, null, company, BaseEnumManager.StateEnum.Enable);

        List<ProcessBrief> processBriefList = searchResult.getList();

        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(ProcessBrief processBrief: processBriefList){
            rMap = new HashMap<String, Object>();
            rMap.put("id", processBrief.getId());
            rMap.put("name", processBrief.getName());
            rMap.put("tableName", entityConfig.getValues(processBrief.getTableKey()));
            rMap.put("creater", processBrief.getCreater() != null ? processBrief.getCreater().getName() : "");
            rMap.put("createDate", DataUtil.DateToString(processBrief.getCreateTime(), "yyyy-MM-dd"));
            rMap.put("state", processBrief.getState().value());
            dataRows.add(rMap);
        }

        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());

        return data;
    }


}
